package com.sohu.tv.controller;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sohu.tv.entity.AppEnum;
import com.sohu.tv.utils.HttpsUtil;
import com.sohu.tv.utils.ServletUtil;

@Controller
@RequestMapping(value="/app")
public class AppController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	//请求平台服务器地址(https请求)
	String url = AppEnum.PLATFORM_URL.toString();
	
	/**
	 * 回调地址处理
	 * @param code server端生成的 code
	 * @param state 原样返回 state
	 * @return
	 */
	@RequestMapping(value="/acquire")
	public String getOppenId(String code,String state,Model model){
		if("".equals(code) && code == null){
			logger.error("获取code失败!");
			model.addAttribute("MSG", "获取code失败");
			return "index";
		}
		String openId = "";
		String token = "";
		//构造请求 token 地址，需要 APPID，APPSECRET，CODE
		String requestUrl = url.replace("APPID", AppEnum.APPID.toString()).replace("APPSECRET",AppEnum.APPSECRET.toString()).replace("CODE", code).replace("STATE", state);
		try {
			HttpSession session = ServletUtil.getHttpSession();
			//发送https请求获取openId与token
			JSONObject jsonObject = HttpsUtil.httpRequest(requestUrl,"GET",null);
			openId = jsonObject.getString("openid");
			token = jsonObject.getString("access_token");
			//获取token以及openid
			if(!"".equals(openId) && !"".equals(token) && null != openId && null != token){
				//将token，openid作为应用的登录凭证。
				session.setAttribute("token", token);
				session.setAttribute("openId", openId);
				return "redirect:/app/info";
			}
		} catch (Exception e) {
			logger.error("获取token失败！错误信息：" + e.getMessage() + " CODE:" + code + " OPRNID:" + openId + " APPID:" + AppEnum.APPID.toString());
			model.addAttribute("MSG", "获取token失败");
		}
		logger.error("获取openId失败！错误信息[CODE:" + code + " OPRNID:" + openId + " APPID:" + AppEnum.APPID.toString() + "]");
		model.addAttribute("MSG", "获取openId失败");
		return "error";
	}
	
	/**
	 * 应用主页
	 * @return
	 */
	@RequestMapping(value="/index")
	public String index(){
		return "index";
	}
	
	/**
	 * 平台登录
	 * @return
	 */
	@RequestMapping(value="/contact_weibo")
	public String contact(){
		String url = AppEnum.LOGIN_URL.toString().replace("APPID", AppEnum.APPID.toString());
		//重定向到开放平台登录页面
		return "redirect:" + url;
	}
	
	/**
	 * 通过token、openId获取个人信息
	 * @return
	 */
	@RequestMapping(value="/info")
	public String info(Model model){
		HttpSession session = ServletUtil.getHttpSession();
		//获取用户openId与token
		String openId = (String) session.getAttribute("openId");
		String token = (String) session.getAttribute("token");
		//判断openId与token是否合法
		if(!"".equals(token) && !"".equals(openId) && null != token && null != openId){
			//使用token以及openid获取开放平台用户信息
			String infoUrl = "https://localhost:441/rest/userinfo?access_token=" + token + "&openId=" + openId;
			JSONObject jsonObject = HttpsUtil.httpRequest(infoUrl,"GET",null);
			String status = jsonObject.getString("status");
			String message = jsonObject.getString("message");
			//openId 与 token 失效
			if("-1".equals(status)){
				model.addAttribute("status", status);
				model.addAttribute("message", message);
				return "info";
			}
			//获取用户信息成功
			model.addAttribute("data", jsonObject.getJSONObject("data"));
			return "info";
		}
		return "index";
	}
}
